package com.css.crm.bean;

import java.util.Date;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.ListDataModel;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;

import com.css.crm.exception.SystemException;
import com.css.crm.message.SystemErrorMessage;
import com.css.crm.message.SystemMessage;
import com.css.crm.utility.ConstantUtil;
import com.css.crm.utility.DateUtil;
import com.css.crm.utility.SelectItemsUtil;
import com.css.crm.utility.SystemUtil;
import com.css.crm.vo.AbstractUser;
import com.css.crm.vo.CustomerVo;
import com.css.db.MyBatisConfig;

/**
 * For search customer function
 * 
 * @author Administrator
 * 
 */
@ManagedBean(name = "updateCustomerBean")
@SessionScoped
public class UpdateCustomerBean extends CustomerBean {

	private ListDataModel<List<CustomerVo>> customerList = new ListDataModel<List<CustomerVo>>();
	private boolean sumTab = false;
	private boolean addTab = false;

	// search
	private String keyWord;

	private boolean cancelledFlag = false;
	
	public UpdateCustomerBean() {
		super();

	}

	/**
	 * query customer by key words user entered.
	 * 
	 * @param event
	 */
	public void searchCustomer(ActionEvent event) {
		if (StringUtils.isEmpty(keyWord)) {
			return;
		}

		try {
			List<CustomerVo> list = customerService.searchCustomerBySolr(keyWord);
			setcustomerList(list);
		} catch (SystemException e) {
			SystemUtil.addMessageError(e.getNewSystemMessage());
			setcustomerList(null);
			return;
		} catch (Exception e) {
			log.error(e.getMessage());
			setcustomerList(null);
			SystemUtil.addMessageError(SystemErrorMessage.SYSTEM_UNEXPECTED_ERROR.getSystemMessage());
			return;
		}

		this.sumTab = true;
		this.addTab = false;

	}

	/**
	 * to edit single record of customer
	 * 
	 * @param event
	 */
	public void toEditCustomer(ActionEvent event) {
		activeTab = "customerTabInfoId";
		String custId = (String) getRequestParameter("custId");
		log.info("edit customer id:" + custId);

		SqlSession session = MyBatisConfig.getSession();
		customerService.setSession(session);
		try {
			customer = customerService.getCustomerByCustId(custId);
			if(ConstantUtil.CUSTOMER_STAT_CODE_C.equals(customer.getStatCde())) {
				cancelledFlag = true;
			} else {
				cancelledFlag = false;
			}
			log.info("query customer id:" + customer.getCustId());
			customer = customerService.setCustomerList(customer);
			log.info("query customer related information end");
			if (customer.getDob() != null) {
				log.info("set customer birthday display");
				customer.setDobMonth(DateUtil.getMonthOfDate(customer.getDob()));
				customer.setDobDay(DateUtil.getDayOfDate(customer.getDob()));
				log.info("set customer birthday display end");
			}

			int month = 1;
			if (StringUtils.isNotEmpty(customer.getDobMonth())) {
				month = Integer.parseInt(customer.getDobMonth());
			}
			dobDayItems = SelectItemsUtil.getDayItems(month);

			// keep the original object
			customer.setOrigiVo(customer.clone());
		} catch (SystemException e) {
			log.error(e.getMessage());
			SystemUtil.addMessageError(e.getNewSystemMessage());
			return;
		} finally {
			session.close();
		}

		if (customer == null) {
			log.info("No customer found.");
			return;
		}

		this.addTab = true;
		this.sumTab = false;

	}

	/**
	 * create or update single customer
	 * 
	 * @param event
	 */
	public void saveCustomer(ActionEvent event) {

		log.info("start save customer");

		SqlSession session = MyBatisConfig.getSession();
		customerService.setSession(session);

		boolean validateResult = customerService.validateCustomer(customer);
		if (!validateResult) {
			return;
		}

		try {
			if (StringUtils.isNotEmpty(customer.getTitle())) {
				if (ConstantUtil.CUSTOMER_TITLE_MR.equals(customer.getTitle())) {
					customer.setSex(ConstantUtil.CUSTOMER_SEX_MALE);
				} else {
					customer.setSex(ConstantUtil.CUSTOMER_SEX_FEMALE);
				}
			}

			if (!StringUtils.isEmpty(this.customer.getCustId())) {

				log.info("update customer.");
				// update customer
				saveUpdateCustomer();
				log.info("end update customer.");

				log.info("update solr document.");
				// update solr index
				solrService.updateDocument(customer);
				log.info("end update solr document.");

			}

			session.commit();

			SystemUtil.addMessage(SystemMessage.SYSTEM_SAVE_SUCCEED.getSystemMessage());

			customer = new CustomerVo();
			this.addTab = false;
			this.sumTab = false;
		} catch (SystemException e) {
			SystemUtil.addMessageError(e.getNewSystemMessage());
			log.error(e.getMessage());
			e.printStackTrace();
		} finally {
			session.close();
		}

	}

	private void saveUpdateCustomer() throws SystemException {
		AbstractUser user = (AbstractUser) SystemUtil.getSession(ConstantUtil.SESSION_USER_KEY);
		customer.setLastModDte(new Date());
		customer.setLastModUser(user.getSmUserId());
		if (StringUtils.isNotEmpty(customer.getDobMonth()) && StringUtils.isNotEmpty(customer.getDobDay())) {
			customer.setDob(DateUtil.parseDate(ConstantUtil.DEFAULT_YEAR_DOB + "-" + customer.getDobMonth() + "-" + customer.getDobDay()));
		}
		customerService.updateCustomer(customer);
		
		if(ConstantUtil.CUSTOMER_STAT_CODE_C.equals(customer.getStatCde())) {
			customerService.updateCustomerCancelled(customer);
		}
		

	}

	public void cancelCustomer(ActionEvent event) {
		customer = new CustomerVo();
		this.addTab = false;

		clearPageData();
	}

	public ListDataModel<List<CustomerVo>> getcustomerList() {
		return customerList;
	}

	public void setcustomerList(List<CustomerVo> customerList) {
		this.customerList.setWrappedData(customerList);
	}

	public boolean isSumTab() {
		return sumTab;
	}

	public void setSumTab(boolean sumTab) {
		this.sumTab = sumTab;
	}

	public boolean isAddTab() {
		return addTab;
	}

	public void setAddTab(boolean addTab) {
		this.addTab = addTab;
	}

	public String getKeyWord() {
		return keyWord;
	}

	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}

	public boolean isCancelledFlag() {
		return cancelledFlag;
	}

	public void setCancelledFlag(boolean cancelledFlag) {
		this.cancelledFlag = cancelledFlag;
	}

	
}
